package me.stone.stanimeclient.page.updated

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.paging.LoadState
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import me.stone.stanimeclient.MainViewModel
import me.stone.stanimeclient.base.AbsViewBindingFragment
import me.stone.stanimeclient.core.common.extensions.launchAndRepeatWithLifecycle
import me.stone.stanimeclient.core.ui.adapters.FanSimpleListAdapter
import me.stone.stanimeclient.databinding.FragmentRecommendOrUpdateBinding
import javax.inject.Inject

@AndroidEntryPoint
class RecentlyUpdatedFanFragment : AbsViewBindingFragment<FragmentRecommendOrUpdateBinding>() {

    @Inject
    lateinit var adapter: FanSimpleListAdapter

    private val mainViewModel by activityViewModels<MainViewModel>()

    private val viewModel by activityViewModels<RecentlyUpdatedFanViewModel>()

    override fun buildViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentRecommendOrUpdateBinding {
        return FragmentRecommendOrUpdateBinding.inflate(inflater, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.list.adapter = adapter.apply {
            toGridStyle()
            setOnItemClickListener {
                mainViewModel.seeFanDetailItem(it.id)
            }
        }

        binding.refresh.setOnRefreshListener {
            adapter.refresh()
        }

        launchAndRepeatWithLifecycle {
            launch {
                viewModel.fans.collectLatest {
                    adapter.submitData(it)
                }
            }

            launch {
                adapter.loadStateFlow.collectLatest {
                    if (binding.refresh.isRefreshing && it.refresh !is LoadState.Loading) {
                        binding.refresh.isRefreshing = false
                    }
                }
            }
        }
    }

}